package com.dyw.mail.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Map;


/**
 * @author Devil
 * @create 2022-02-21 14:37
 */
@Slf4j
@Service
public class MailService {

    @Value("${spring.mail.username}")
    private String form;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private TemplateEngine templateEngine;


    public void sendSimpleTextMail(String to, String subject, String content){
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        for (int i = 0; i < 100; i++) {
            simpleMailMessage.setTo(to);
            simpleMailMessage.setSubject(subject+i);
            simpleMailMessage.setText(content+i);
            simpleMailMessage.setFrom(form);

            javaMailSender.send(simpleMailMessage);
            log.info("文本邮件发送成功! to={}",to);
        }

    }
    public void sendSimpleTextMail(String to, String subject, Map<String,Object> paramMap, String template) throws MessagingException{
        Context context = new Context();
        //设置变量的值
        context.setVariables(paramMap);
        String emailContent = templateEngine.process(template,context);
        sendHtmlMail(to,subject,emailContent);
        log.info("[模板邮件]成功发送! paramMap={},template={}",paramMap,template);
    }
    public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        mimeMessageHelper.setFrom(form);
        mimeMessageHelper.setTo(to);
        mimeMessageHelper.setSubject(subject);

        //true 为html邮件
        mimeMessageHelper.setText(content,true);
        javaMailSender.send(mimeMessage);
        log.info("[html邮件]发送成功! to={}",to);
    }
}
